<template>
  <div class="drag" ref="dragDiv">
    <div class="drag_text">{{ msg }}</div>
    <div
      ref="moveDiv"
      @touchstart="touchstart($event)"
      @touchmove="touchmove($event)"
      @touchend="touchend($event)"
      class="block block_bg"
      :class="{ block_ok_bg: is_success }"
    ></div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["unlock"]);
let is_success = ref(false);
// 拖动的最大的宽度,根据滑动块的宽度去计算
let maxWidth = "";
let Xstart = 0;
let msg = ref("请滑动解锁");

onMounted(() => {
  maxWidth = proxy.$refs.dragDiv.clientWidth - proxy.$refs.moveDiv.clientWidth;
  console.log(maxWidth);
});

function touchstart(e) {
  //   console.log(e);
  e.preventDefault && e.preventDefault();
  if (!is_success.value) {
    Xstart = e.touches[0].clientX;
  }
}
function touchmove(e) {
  e.preventDefault && e.preventDefault();
  if (!is_success.value) {
    let Xmove = e.changedTouches[0].clientX;
    if (Xmove - Xstart < maxWidth) {
      proxy.$refs.moveDiv.style.left = Xmove - Xstart + "px";
    } else {
      proxy.$refs.moveDiv.style.left = maxWidth + "px";
    }
  }
}
function touchend(e) {
  e.preventDefault && e.preventDefault();
  if (!is_success.value) {
    if (e.changedTouches[0].clientX - Xstart < maxWidth) {
      proxy.$refs.moveDiv.style.left = "0px";
    } else {
      msg.value = "解锁成功";
      is_success.value = true;
      emits("unlock");
    }
  }
}
</script>

<style lang="scss" scoped>
.drag {
  position: relative;
  background-color: #ebebeb;
  width: 100%;
  height: 42px;
  line-height: 42px;
  text-align: center;
  .block {
    width: 69px;
    height: 42px;
    cursor: move;
    position: absolute;
    top: 0;
    left: 0;
  }
  .block_bg {
    background: lightgray url("../assets/image/slideBlock.png") no-repeat center;
    background-size: 20px 20px;
  }
  .block_ok_bg {
    background: lightgray url("../assets/image/success.png") no-repeat center;
    background-size: 20px 20px;
  }
}
</style>